# -*- coding: utf-8 -*-
import hashlib
import json
import random
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '101252': {  # witch
        'API_KEY': '1719f23ab1730fe984192c0d5eee2139',
        'gateway': ' https://pay.api11.com',
        'query_gateway': 'https://pay.api11.com/Index/query.html',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign

# MerchantCode = [xxxx]
# OrderId = [xxxx]
# Amount = [xxxx]
# NotifyUrl = [xxxx]
# OrderDate = [xxxx]
# BankCode = [xxxx]
# TokenKey = [MerchantKey]
def generate_sign(d, key):
    s = 'MerchantCode=[{}]OrderId=[{}]Amount=[{}]NotifyUrl=[{}]OrderDate=[{}]BankCode=[{}]TokenKey=[{}]'.format(
        d['MerchantCode'], d['OrderId'], d['Amount'], d['NotifyUrl'], d['OrderDate'], d['BankCode'], key)
    _LOGGER.info("boshipay sign str: %s", s)
    return _gen_sign(s)


# MerchantCode = [xxxx]
# OrderId = [xxxx]
# OutTradeNo = [xxxx]
# Amount = [xxxx]
# OrderDate = [xxxx]
# BankCode = [xxxx]
# Remark = [xxxx]
# Status = [xxxx]
# Time = [xxxx]
# TokenKey = [MerchantKey]
def generate_notify_sign(d, key):
    s = 'MerchantCode=[{}]OrderId=[{}]OutTradeNo=[{}]Amount=[{}]OrderDate=[{}]BankCode=[{}]Remark=[{}]Status=[{}]Time=[{}]TokenKey=[{}]'.format(
        d['MerchantCode'], d['OrderId'], d['OutTradeNo'], d['Amount'], d['OrderDate'], d['BankCode'], d['Remark'],
        d['Status'], d['Time'], key)
    _LOGGER.info("boshipay sign str: %s", s)
    return _gen_sign(s)


# MerchantCode=[xxxx]OrderId=[xxxx]Time=[xxxx]TokenKey=[MerchantKey]
def generate_query_sign(d, key):
    s = 'MerchantCode=[{}]OrderId=[{}]Time=[{}]TokenKey=[{}]'.format(
        d['MerchantCode'], d['OrderId'], d['Time'], key)
    _LOGGER.info("boshipay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['Sign']
    params.pop('Sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("boshipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# WECHAT	微信扫码
# WECHAT_BARCODE	微信条形码
# WECHAT_WAP	手机微信
# ALIPAY_WAP	手机支付宝
# ALIPAY	支付宝扫码
# QQ_WAP	QQ手机
# QQ	QQ扫码
# JD_WAP	京东手机
# JD	京东扫码
# CUP	银联扫码
# EXPRESS	银联快捷
# MIB	手机网银
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'WECHAT_WAP'
    elif service == 'alipay':
        payType = 'ALIPAY_WAP'
    elif service == 'qq':
        payType = 'QQ_WAP'
    elif service == 'quick':
        payType = 'EXPRESS'
    else:
        payType = 'JD_WAP'
    return payType


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def _fix_pay_amount(pay, pay_amount):
    extend = json.loads(pay.extend or '{}')
    if pay_amount >= 10 and int(pay_amount) == pay_amount:
        discount = random.randint(1, 10)
        pay_amount = pay_amount - float(discount)/100
        extend.update({'discount': str(float(discount) / 100)})
        order_db.fill_extend(pay.id, extend)
    return pay_amount


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    # pay_amount = _fix_pay_amount(pay, pay_amount)
    parameter_dict = OrderedDict((
        ('MerchantCode', app_id),
        ('BankCode', _get_pay_type(service)),
        ('Amount', '%.2f' % pay_amount),
        ('OrderId', str(pay.id)),
        ('NotifyUrl', '{}/pay/api/{}/boshipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('OrderDate', int(time.time())),
        ('Remark', 'charge'),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("boshipay create: %s", parameter_dict)
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("boshipay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['OrderId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('boshipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['Status'])
    trade_no = data['OutTradeNo']
    total_fee = float(data['Amount'])
    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 1:成功 ，0:失败
    if trade_status == '1':
        _LOGGER.info('boshipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('Time', int(time.time())),
        ('OrderId', str(pay_order.id)),
        ('MerchantCode', app_id),
    ))
    parameter_dict['Sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info('boshipay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('boshipay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['status'])
        total_fee = float(data['moneyreceived'])
        trade_no = data['outorderid']

        discount = float(json.loads(pay_order.extend or '{}').get('discount', 0))
        extend = {
            'discount': discount,
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        # 1 处理中 2 成功 3失败
        if trade_status == '2':
            _LOGGER.info('boshipay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
